<template>
  <div class="table-gl-w">
    <a-tabs @change="changeStatus">
      <a-tab-pane v-for="tab in tabsList" :key="tab.key">
        <template #title>
          <span>{{ tab.title }}</span>
        </template>
      </a-tab-pane>
    </a-tabs>
    <div class="search-w table-filter-form">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getTableList">
        <template #headerLeft>
          <a-space>
            <a-button type="primary" size="medium" @click="openAddQuotation" v-if="searchVal.status == 1 && $authPass('procurement.supplier.quote.save')">新增报价</a-button>
            <a-button class="gray-outline" size="medium" @click="submitAudit(selectIds)" v-if="searchVal.status == 1 && $authPass('procurement.supplier.quote.edit')">提交审核</a-button>
            <a-button type="primary" size="medium" @click="openAuditDialog(selectIds)" v-if="searchVal.status == 20 && $authPass('procurement.supplier.quote.audit')">审核</a-button>
            <a-button class="gray-outline" size="medium" @click="submitRevocation(selectIds)" v-if="searchVal.status == 10">撤回草稿</a-button>
            <a-button type="primary" size="medium" @click="openChangePriceBatch()" v-if="searchVal.status == 30 && $authPass('procurement.supplier.quote.change')">批量变更</a-button>
          </a-space>
        </template>
        <template #tableBody>
          <span class="expand-all-btn" v-if="tableList.length" @click="changeExpandAll">
            <icon-plus v-show="!expandAll" />
            <icon-minus v-show="expandAll" />
          </span>
          <a-table class="table-two-line" ref="tableListref" row-key="id" :expandable="expandable" :loading="tableLoading" @selection-change="selectColumn" :row-selection="rowSelection" :bordered="false" :columns="tableColumns" :data="tableList" size="mini" :pagination="false" :scroll="{ x: '100%', y: '100%' }">
            <template #columns>
              <a-table-column title="序号" :width="45" fixed="left" key="index">
                <template #cell="{ rowIndex }">
                  <p>{{ rowIndex + 1 }}</p>
                </template>
              </a-table-column>
              <a-table-column title="报价ID" :width="100" fixed="left" key="billNo">
                <template #cell="{ record }">
                  <a-space :size="4">
                    <p class="highlight cursor" @click="toDetail(record)">{{ record.billNo }}</p>
                    <CopyText class="popup-edit-icon-hover" :val="record.billNo" />
                  </a-space>
                </template>
              </a-table-column>
              <a-table-column title="经销商" data-index="companyName" :width="120" fixed="left" key="companyName" />
              <a-table-column title="报价类型" :width="80" key="quoteType">
                <template #cell="{ record }">
                  <p>{{ record.quoteType === 1 ? '非梯度报价' : '梯度报价' }}</p>
                </template>
              </a-table-column>
              <a-table-column title="发票类型" :width="80" key="invoiceType">
                <template #cell="{ record }">
                  <p>{{ invoiceTypeMap[record.invoiceType] }}</p>
                </template>
              </a-table-column>
              <a-table-column title="税率" :width="70" key="parTaxRate">
                <template #cell="{ record }">
                  <p>{{ record.parTaxRate }}%</p>
                </template>
              </a-table-column>
              <a-table-column title="含税单价" :width="100" key="taxPrice">
                <template #cell="{ record }">
                  <p>{{ getTaxPrice(record) }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="currency" title="币种" :width="50" key="currency" />
              <a-table-column title="交期" :width="60" key="deliveryDays">
                <template #cell="{ record }">
                  <p>{{ record.deliveryDays }}天</p>
                </template>
              </a-table-column>
              <a-table-column data-index="moq" title="起订量" :width="70" key="moq" />
              <a-table-column data-index="purchaseUname" title="采购员" :width="70" key="purchaseUname" />
              <a-table-column data-index="createUname" title="创建人" :width="70" key="createUname" />
              <a-table-column title="创建时间" :width="140" key="gmtCreate">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.gmtCreate) }}</p>
                </template>
              </a-table-column>
              <a-table-column title="供应商审核" :width="200" data-index="auth1" key="auth1" v-if="searchVal.status === 1">
                <template #cell="{ record }">
                  <template v-if="record.supplierAuditUname">
                    <p>
                      <span>【{{ record.supplierAuditUname }}】</span>
                      <span>{{ auditMap[record.supplierAudit] }}，</span>
                      <span>{{ $setTime(record.gmtSupplierAudit, 'YYYY/MM/DD HH:MM') }}</span>
                    </p>
                    <TextLimit :rows="1">{{ record.supplierAuditRemark }}</TextLimit>
                  </template>
                  <p v-else>--</p>
                </template>
              </a-table-column>
              <a-table-column title="经销商审核" :width="210" data-index="auth" key="auth" v-if="searchVal.status === 1">
                <template #cell="{ record }">
                  <template v-if="record.companyAuditUname">
                    <p>
                      <span>【{{ record.companyAuditUname }}】</span>
                      <span>{{ auditMap[record.companyAudit] }}，</span>
                      <span>{{ $setTime(record.gmtCompanyAudit, 'YYYY/MM/DD HH:MM') }}</span>
                    </p>
                    <TextLimit :rows="1">{{ record.companyAuditRemark }}</TextLimit>
                  </template>
                  <p v-else>--</p>
                </template>
              </a-table-column>
              <a-table-column title="操作" :width="90" key="handle">
                <template #cell="{ record }">
                  <a-space>
                    <a-button type="text" @click="openEditDialog(record)" v-if="record.status == 1 && $authPass('procurement.supplier.quote.edit')">编辑</a-button>
                    <a-button type="text" @click="openAuditDialog([record.id])" v-else-if="record.status == 20 && $authPass('procurement.supplier.quote.audit')">审核</a-button>
                    <a-button type="text" @click="submitRevocation([record.id])" v-else-if="record.status == 10">撤回草稿</a-button>
                    <a-button type="text" @click="toDetail(record)" v-else>详情</a-button>
                    <a-dropdown>
                      <icon-more class="table-btn-more" />
                      <template #content>
                        <a-doption @click.stop="submitAudit([record.id])" v-if="record.status == 1 && $authPass('procurement.supplier.quote.edit')">提交审核</a-doption>
                        <a-doption @click.stop="submitCancellation([record.id])" v-if="[1].includes(record.status) && $authPass('procurement.supplier.quote.delete')">删除</a-doption>
                        <a-doption @click.stop="toDetail(record)" v-if="[10, 20].includes(record.status)">详情</a-doption>
                        <a-doption @click.stop="openChangePriceSingle(record)" v-if="record.status == 30 && $authPass('procurement.supplier.quote.change')">变更报价</a-doption>
                        <a-doption @click.stop="openChangeProduct(record)" v-if="record.status == 30 && $authPass('procurement.supplier.quote.change')">变更产品</a-doption>
                        <a-doption @click.stop="openLogList(record)">日志</a-doption>
                      </template>
                    </a-dropdown>
                  </a-space>
                </template>
              </a-table-column>
            </template>
            <template #expand-row="{ record }">
              <div class="product-w">
                <a-table class="table-singe-line" row-class="child-row" row-key="id" :bordered="false" :columns="tableColumns" :data="record.quoteProducts" size="mini" :pagination="false">
                  <template #columns>
                    <a-table-column v-for="(item, index) of tableColumns" :key="index" :fixed="item.fixed" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
                      <template v-if="item.dataIndex == 'img'" #cell="option">
                        <ImgPopover :src="option.record.productImg">
                          <template #con>
                            <a-image width="40" height="40" fit="contain" :src="option.record.productImg" />
                          </template>
                        </ImgPopover>
                      </template>
                      <template v-else-if="item.dataIndex == 'productName'" #cell="option">
                        <TextLimit>{{ option.record.productName }}</TextLimit>
                      </template>
                    </a-table-column>
                  </template>
                </a-table>
              </div>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <!-- 添加编辑报价 -->
  <SupAddAndEditQuotation v-if="showAddAndEditDialog" :dealerList="dealerList" :isShow="showAddAndEditDialog" :currentItem="currentData" @closed="showAddAndEditDialog = false" @success="getTableList" />
  <!-- 报价详情 -->
  <SupQuotationDetail v-if="showDetailDialog" :isShow="showDetailDialog" :currentItem="currentData" @closed="showDetailDialog = false" />
  <!-- 审核 -->
  <SupAudit v-if="showAuditDialog" :isShow="showAuditDialog" @closed="showAuditDialog = false" @success="audit" />
  <!-- 日志列表 -->
  <CommonLogsDialog v-if="showLogDialog" api="findSupplierQuoteLogPage" :id="currentData.id" :isShow="showLogDialog" @closed="showLogDialog = false" />
  <!-- 变更报价 -->
  <SupChangePriceSingle v-if="showChangePriceSingle" :isShow="showChangePriceSingle" :currentItem="currentData" @closed="showChangePriceSingle = false" />
  <!-- 变更产品 -->
  <SupChangeProduct v-if="showChangeProduct" :isShow="showChangeProduct" :currentItem="currentData" @closed="showChangeProduct = false" />
  <!-- 批量变更报价 -->
  <SupChangePriceBatch v-if="showChangePriceBatch" :isShow="showChangePriceBatch" :currentList="currentList" @closed="showChangePriceBatch = false" />
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { FilterTableItem } from '@/types/components'
  import FilterTable from '@/components/TableFilter.vue'
  import CommonLogsDialog from '@/components/Log/logsDialog.vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import { findSupplierQuotePage, findDealerList, commitSupplierQuote, deleteSupplierQuote, auditSupplierQuote, revokeSupplierQuote } from '@/api/supplier'
  import SupAddAndEditQuotation from './components/supAddAndEditQuotation.vue'
  import SupChangePriceSingle from './components/supChangePriceSingle.vue'
  import SupChangePriceBatch from './components/supChangePriceBatch.vue'
  import SupChangeProduct from './components/supChangeProduct.vue'
  import SupQuotationDetail from './components/supQuotationDetail.vue'
  import SupAudit from './components/supAudit.vue'
  import { currencySymbol } from '@/utils/globalData'

  onMounted(async () => {
    getDealerList()
    getTableList()
    getCurrencyList()
  })
  const tableColumns: Array<any> = [
    {
      title: '图片',
      dataIndex: 'img',
      width: 60,
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      width: 140,
    },
    {
      title: '类目',
      dataIndex: 'cateName',
      width: 100,
    },
    {
      title: '经销商SKU',
      dataIndex: 'sku',
      width: 130,
    },
    {
      title: '经销商SPU',
      dataIndex: 'spu',
      width: 130,
    },
    {
      title: '供应商SKU',
      dataIndex: 'ssku',
      width: 130,
    },
    {
      title: '供应商SPU',
      dataIndex: 'sspu',
      width: 130,
    },
  ]
  const expandable = ref<any>({
    width: 40,
    title: '',
  })
  const tabsList = [
    { key: 1, title: '草稿' },
    { key: 20, title: '待供应商审核' },
    { key: 10, title: '待经销商审核' },
    { key: 30, title: '已生效' },
  ]
  const auditMap = {
    '0': '未审核',
    '1': '同意',
    '-1': '驳回',
  }
  const filterItem = ref<Array<FilterTableItem>>([
    {
      type: 'input_keyword',
      key: 'skus',
      keyItems: [
        { label: '经销商SKU', value: 'skus' },
        { label: '经销商SPU', value: 'spus' },
        { label: '供应商SKU', value: 'sskus' },
        { label: '供应商SPU', value: 'sspus' },
        { label: '产品名称', value: 'productName' },
      ],
      keyWidth: '120',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 160,
      isMultiple: true,
    },
    {
      key: 'billNo',
      label: '报价ID',
      value: ref(),
      type: 'input_search',
      width: 140,
    },
    {
      key: 'dealerId',
      label: '经销商',
      value: ref(),
      type: 'select',
      width: 140,
      optionItems: [],
    },
    {
      key: 'currency',
      label: '币种',
      value: ref(),
      type: 'select',
      width: 100,
      optionItems: [],
    },
    {
      key: 'invoiceType',
      label: '发票类型',
      value: ref(),
      type: 'select',
      width: 100,
      optionItems: [
        { label: '普票', value: '1' },
        { label: '专票', value: '2' },
        { label: '不开票', value: '0' },
      ],
    },
    {
      key: 'quoteType',
      label: '报价类型',
      value: ref(),
      type: 'select',
      width: 100,
      optionItems: [
        { label: '梯度价', value: '2' },
        { label: '非梯度价', value: '1' },
      ],
    },
    {
      type: 'keyword_date_range',
      key: 'gmtWrite',
      keyItems: [
        { label: '创建日期', value: 'gmtCreate' },
        { label: '更新日期', value: 'gmtWrite' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '创建时间',
      width: 240,
      attrs: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
  ])
  const rowSelection = ref({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  let searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
    status: 1,
  })
  const invoiceTypeMap = {
    0: '不开票',
    1: '普票',
    2: '专票',
  }
  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const total = ref(0)
  const selectIds = ref([])
  const currentData = ref<any>({})
  const currentIds = ref<Array<any>>([])
  const currentList = ref<Array<any>>([])
  const showAddAndEditDialog = ref(false)
  const showAuditDialog = ref(false)
  const showLogDialog = ref(false)
  const dealerList = ref<Array<any>>([])
  const filterData = ref<any>({})
  const tableListref = ref()
  const expandAll = ref(false)
  const showDetailDialog = ref(false)
  const showChangePriceSingle = ref(false)
  const tableListMap: any = {}
  const showChangeProduct = ref(false)
  const showChangePriceBatch = ref(false)

  //  币种列表
  function getCurrencyList() {
    let options = Object.keys(currencySymbol).map((key: string) => {
      return {
        label: key,
        value: key,
      }
    })
    filterItem.value[3].optionItems = options
  }
  //经销商列表
  async function getDealerList() {
    const res: any = await findDealerList()
    dealerList.value = res?.data || []
    filterItem.value[2].optionItems = res?.data?.map((el: any) => {
      return {
        label: el.dealerName,
        value: el.id,
      }
    })
  }

  // 折叠展开全部
  function changeExpandAll() {
    expandAll.value = !expandAll.value
    tableListref.value.expandAll(expandAll.value)
  }
  // 通过条件查询列表
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }
  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 切换状态
  function changeStatus(status: number | string) {
    searchVal.value.status = status
    searchVal.value.pageNum = 1
    getTableList()
  }

  // 获取商品列表
  async function getTableList() {
    let params = {
      ...searchVal.value,
      ...filterData.value,
    }
    tableLoading.value = true
    const res: any = await findSupplierQuotePage(params)
    tableListref.value.selectAll(false)
    tableLoading.value = false
    tableList.value = res?.data?.records || []
    tableListMap.value = {}
    tableList.value.forEach((el) => {
      tableListMap.value[el.id] = el
    })
    total.value = res?.data?.total || 0
  }
  // 添加供应商报价
  function openAddQuotation() {
    currentData.value = {}
    showAddAndEditDialog.value = true
  }
  // 撤回草稿
  function submitRevocation(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择报价')
      return
    }
    Modal.confirm({
      title: '撤回草稿',
      content: `请再次确认是否需要把选中的报价撤回到草稿箱`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await revokeSupplierQuote({ ids: ids })
        if (res) {
          Message.success('撤回草稿箱成功')
          getTableList()
        }
      },
    })
  }
  // 提交审核
  function submitAudit(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择报价')
      return
    }
    Modal.confirm({
      title: '提交审核',
      content: `请再次确认是否将选中报价提交审核`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await commitSupplierQuote({ ids: ids })
        if (res) {
          Message.success('提交审核成功')
          getTableList()
        }
      },
    })
  }
  // 删除
  function submitCancellation(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择报价')
      return
    }
    Modal.confirm({
      title: '删除',
      content: `请再次确认是否需要删除选中的报价`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await deleteSupplierQuote({ ids: ids })
        if (res) {
          Message.success('删除成功')
          getTableList()
        }
      },
    })
  }
  // 显示报价
  function getTaxPrice(row: any) {
    let currency = currencySymbol[row.currency]
    if (row.quoteType === 1) {
      // 非梯度报价
      return currency + row?.quoteItems?.[0]?.taxPrice
    } else {
      // 梯度报价
      let taxPrices: Array<any> = row?.quoteItems?.map((el: any) => el.taxPrice)
      let max = Math.max.apply(null, taxPrices)
      let min = Math.min.apply(null, taxPrices)
      return `${currency}${min} ~ ${currency}${max}`
    }
  }
  // 打开编辑报价
  function openEditDialog(row: any) {
    currentData.value = row
    showAddAndEditDialog.value = true
  }
  // 打开变更报价
  function openChangePriceSingle(row: any) {
    currentData.value = row
    showChangePriceSingle.value = true
  }
  // 打开变更产品
  function openChangeProduct(row: any) {
    currentData.value = row
    showChangeProduct.value = true
  }
  // 报价详情
  function toDetail(row: any) {
    currentData.value = row
    showDetailDialog.value = true
  }
  // 打开日志列表
  function openLogList(row: any) {
    currentData.value = row
    showLogDialog.value = true
  }
  // 打开审核弹窗
  function openAuditDialog(ids: any) {
    if (!ids.length) {
      Message.error('请选择报价')
      return
    }
    currentIds.value = ids
    showAuditDialog.value = true
  }
  // 打开批量变更报价
  function openChangePriceBatch() {
    if (!selectIds.value.length) {
      Message.error('请选择报价')
      return
    }
    currentList.value = []
    selectIds.value.map((id) => {
      currentList.value.push(tableListMap.value[id])
    })
    showChangePriceBatch.value = true
  }
  // 开始审核
  async function audit(auditRes: any) {
    const res: any = await auditSupplierQuote({
      ids: currentIds.value,
      pass: auditRes.state,
      remark: auditRes.result,
    })
    if (res) {
      Message.success(auditRes.state ? '审核通过' : '已驳回')
      getTableList()
    }
  }
</script>
<style lang="less" scoped>
  :deep(.arco-tabs-nav-tab) {
    background-color: #fff;
  }
  :deep(.arco-table-tr-expand .arco-table-td) {
    background-color: #fff;
  }
  :deep(.arco-table-tr-expand:hover .arco-table-td) {
    background-color: transparent !important;
  }
  .expand-all-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 14px;
    height: 14px;
    padding: 0;
    color: var(--color-text-2);
    font-size: 12px;
    line-height: 14px;
    background-color: var(--color-neutral-3);
    border: 1px solid transparent;
    border-radius: 2px;
    outline: none;
    cursor: pointer;
    transition: background-color 0.1s cubic-bezier(0, 0, 1, 1);
    position: absolute;
    top: 22px;
    left: 23px;
    z-index: 100;
  }
  :deep(.table-con) {
    position: relative;
  }
  .product-w {
    margin: 5px 0;
    background-color: rgb(var(--gray-2)) !important;
    .arco-table {
      width: 100%;
      margin: 0 !important;
      :deep(.child-row:hover .arco-table-td) {
        background-color: rgba(var(--primary-1), 0.5) !important;
      }
    }
  }
</style>
